package com.miyuan.wm.exception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.miyuan.wm.enums.ExceptionCodeEnum;

/**
 * 自定义异常
 *
 *
 */
@Slf4j
public class MyExceptionHandler implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		ModelAndView mv = new ModelAndView();
		FastJsonJsonView view = new FastJsonJsonView();
		Map<String, Object> attributes = new HashMap<String, Object>();
		if (ex instanceof UnauthenticatedException) {
			attributes.put("errCode", ExceptionCodeEnum.TOKEN_ERROR.getCode());
			attributes.put("errMsg", ExceptionCodeEnum.TOKEN_ERROR.getMsg());
		} else if (ex instanceof UnauthorizedException) {
			attributes.put("errCode", ExceptionCodeEnum.USER_NO_UNAUTHORIZED_ERROR.getCode());
			attributes.put("errMsg", ExceptionCodeEnum.USER_NO_UNAUTHORIZED_ERROR.getMsg());
		} else if (ex instanceof BaseException) {
			attributes.put("errCode", ((BaseException) ex).getCode());
			attributes.put("errMsg", ((BaseException) ex).getMsg());
		} else {
			attributes.put("errCode", ExceptionCodeEnum.SYS_ERROR.getCode());
			attributes.put("errMsg", ExceptionCodeEnum.SYS_ERROR.getMsg());
		}
		log.error("异常", ex);
		view.setAttributesMap(attributes);
		mv.setView(view);
		return mv;
	}

}
